package org.ala.tiktools.mybatis.expand.binding;

import org.ala.tiktools.mybatis.expand.ExpandData;
import org.ala.tiktools.mybatis.pager.Pager;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cursor.Cursor;
import org.apache.ibatis.reflection.ParamNameResolver;
import org.apache.ibatis.reflection.TypeParameterResolver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * 扩展mybatis的MethodSignature
 *
 * @author ala
 * @date 2025-01-10 11:25
 */
public class MethodSignatureExpander extends MapperMethod.MethodSignature {

    protected boolean returnsPager;

    public MethodSignatureExpander(Configuration configuration, Class<?> mapperInterface, Method method) {
        super(configuration, mapperInterface, method);
        //  Pager的子类，返回的也是many
        returnsPager = Pager.class.isAssignableFrom(getReturnType());
    }

    /**
     * 扩展是否returnsMany
     * <p>  如果返回类型搜Pager，判定也是many
     */
    public boolean returnsPager() {
        return returnsPager;
    }


    /**
     * 解析成mybatis参数
     * <p>  只关心解析成map的参数
     * @param args
     * @param appendData
     * @return
     */
    public Object convertArgsToSqlCommandParam(Object[] args, Map<String, ExpandData> appendData) {
        Object param = super.convertArgsToSqlCommandParam(args);
        if (!(param instanceof Map)) {return param;}

        Map<String, Object> map = (Map<String, Object>) param;
        //  解析appendData中的expandToMybatis参数
        appendData.forEach((k,v) -> {
            if (v.isExpandToMBatis()) {
                map.put(v.getKey(), v.getValue());
            }
        });
        return map;
    }

    public RowBounds extractRowBounds(Object[] args, Map<String, ExpandData> appendData) {
        return super.extractRowBounds(args);
    }

    public ResultHandler extractResultHandler(Object[] args, Map<String, ExpandData> appendData) {
       return super.extractResultHandler(args);
    }
}
